package com.core.reach.cloudhub.lb.impl;

import com.core.reach.cloudhub.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ga.zhang
 * @version V1.0
 * @description: 自定义轮询负载均衡模式
 * @date 2020/3/25 15:19
 **/
@Slf4j
@Component
public class CustomLoadBalancer implements LoadBalancer {

    private AtomicInteger nextServerIndex = new AtomicInteger(0);

    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstances) {
        int index = serviceInstances.size() == 0 ? -1 : getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }

    private int getAndIncrement() {
        int current;
        int next;
        do {
            current = nextServerIndex.get();
            next = current >= 2147483647 ? 0 : current + 1;
        } while (!nextServerIndex.compareAndSet(current, next));
        log.info("*************next:{}", next);
        return next;
    }

}
